from django.shortcuts import render
from django.shortcuts import redirect
from django.shortcuts import reverse
from django.shortcuts import HttpResponse
from django import views
from django.db import DatabaseError
from rbac import models
from rbac.forms.role import RoleModleForm


class RoleListView(views.View):
    '''
    角色查看
    '''
    def get(self,request):
        data_list=models.Role.objects.all()
        return render(request,'rbac/role_list.html',{'data_list':data_list})


class RoleAddView(views.View):
    '''
    角色添加
    '''
    def get(self,request):
        role_model_form=RoleModleForm()

        return render(request,'rbac/role_add.html',{'form':role_model_form})
    def post(self,request):
        role_model_form=RoleModleForm(data=request.POST)
        if role_model_form.is_valid():
            role_model_form.save()
            return redirect(reverse('rbac:role_list'))
        else:
            return render(request,'rbac/role_add.html',{'form':role_model_form})

class RoleEditView(views.View):
    '''
    角色编辑
    '''
    def get(self,request,pk):
        role_obj=models.Role.objects.get(pk=pk)
        role_model_form=RoleModleForm(instance=role_obj)
        return render(request,'rbac/role_edit.html',{'form':role_model_form})
    def post(self,request,pk):
        role_obj=models.Role.objects.get(pk=pk)
        role_model_form=RoleModleForm(instance=role_obj,data=request.POST)
        if role_model_form.is_valid():
            role_model_form.save()
            return redirect(reverse('rbac:role_list'))
        else:
            return render(request,'rbac/role_edit.html',{'form':role_model_form})

class RoleDeleteView(views.View):
    '''
    角色删除
    '''
    def get(self,request,pk):
        return render(request,'rbac/role_delete.html')
    def post(self,request,pk):
        try:
            models.Role.objects.filter(pk=pk).delete()
            return redirect(reverse('rbac:role_list'))
        except DatabaseError:
            return HttpResponse('删除失败')